package org.grottarossa.data.impl;


import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;

import org.apache.log4j.Logger;
import org.grottarossa.data.CasefolderDAO;
import org.grottarossa.domain.CaseFolder;

/**
 * Implementation of casefolder data access object with JDO capabilities
 * */
public class CaseFolderDAOImpl extends GenericDAO implements CasefolderDAO 
{
	Logger logger = Logger.getLogger(CaseFolderDAOImpl.class.getName());

	public CaseFolderDAOImpl() 
	{
	}

	public String createCaseFolder(CaseFolder casefolder) {

		PersistenceManager pm = this.persistenceManagerFactory
				.getPersistenceManager();
		CaseFolder caseF = null;
		try {
			pm.currentTransaction().begin();
			
			caseF = pm.makePersistent(casefolder);
			
			pm.currentTransaction().commit();
		} catch (Exception e) {
			// TODO cath exception
			pm.currentTransaction().rollback();
		} finally {
			if (pm.currentTransaction().isActive()) {
				pm.currentTransaction().rollback();
			}
			pm.close();
		}
		return caseF.getId();
	}

	public void updateCaseFolder(CaseFolder casefolder) {
		
		CaseFolder caseUpd = (CaseFolder) casefolder.cloneObj();
		
		PersistenceManager pm = this.persistenceManagerFactory
				.getPersistenceManager();
		try {
			pm.currentTransaction().begin();
			CaseFolder caseVo = pm.getObjectById(CaseFolder.class,
					casefolder.getId());
			caseVo.update(caseUpd);
			pm.currentTransaction().commit();
		} catch (Exception e) {
			// TODO cath exception
			pm.currentTransaction().rollback();
		} finally {
			if (pm.currentTransaction().isActive()) {
				pm.currentTransaction().rollback();
			}
			pm.close();
		}
	}

	public void removeCaseFolder(CaseFolder caseFolder) 
	{
		PersistenceManager pm = this.persistenceManagerFactory
				.getPersistenceManager();
		try {
			pm.currentTransaction().begin();
			
			pm.deletePersistent(caseFolder);
			
			pm.currentTransaction().commit();
		}
		catch (Exception e) 
		{
			pm.currentTransaction().rollback();
		} finally {
			if (pm.currentTransaction().isActive()) {
				pm.currentTransaction().rollback();
			}
			pm.close();
		}	
	}

	public CaseFolder getCaseFolderById(String casefolder_id) {
		PersistenceManager pm = this.persistenceManagerFactory
				.getPersistenceManager();
		CaseFolder caseVo = null;
		try {
			pm.getFetchPlan().setMaxFetchDepth(-1);
			pm.getFetchPlan().addGroup("field-fetch-group");
			pm.currentTransaction().begin();
			caseVo = pm.getObjectById(CaseFolder.class, casefolder_id);
			caseVo = pm.detachCopy(caseVo);
			pm.currentTransaction().commit();
		}

		catch (Exception e) {
			// TODO cath exception
			pm.currentTransaction().rollback();
		} finally {
			if (pm.currentTransaction().isActive()) {
				pm.currentTransaction().rollback();
			}
			pm.close();
		}
		return (caseVo);

	}
}
